package db

import (
	"fmt"
	"project/PersonalBlog/model"
)

//SelectComments ..获取评论
func SelectComments(id int64) (comments []*model.Comment) {
	rows, err := Stmt[StmtGetComments].Query(id)
	if err != nil {
		fmt.Println("db.SelectComments--->", err.Error())
		return nil
	}
	defer rows.Close()
	for rows.Next() {
		com := &model.Comment{ID: id}
		//Icontent,username,create_time
		err := rows.Scan(&com.Content, &com.UserName, &com.CreateTime)
		if err != nil {
			fmt.Println("db.SelectComments--->", err.Error())
			continue
		}
		comments = append(comments, com)
	}
	return
}

//InsertComment ..插入评论 成功返回id号  不成功返回-1
func InsertComment(c *model.Comment) (id int64) {
	row, err := Stmt[StmtInsertComment].Exec(c.ArticleID, c.Content, c.UserName, c.Email)
	if err != nil {
		fmt.Println("db.InsertComment--->", err.Error())
		return -1
	}
	id, err = row.LastInsertId()
	if err != nil {
		fmt.Println("db.InsertComment--->", err.Error())
		return -1
	}
	return
}

//InsertCommentWD ..留言给作者wd
func InsertCommentWD(c *model.Comment) (id int64) {
	row, err := Stmt[StmtInsertLeave].Exec(c.UserName, c.Email, c.Content)
	if err != nil {
		fmt.Println("db.InsertComment--->", err.Error())
		return -1
	}
	id, err = row.LastInsertId()
	if err != nil {
		fmt.Println("db.InsertComment--->", err.Error())
		return -1
	}
	return
}

//SelectCommentsWD ..获取评论
func SelectCommentsWD() (comments []*model.Comment) {
	rows, err := Stmt[StmtGetLeaves].Query()
	if err != nil {
		fmt.Println("db.SelectComments--->", err.Error())
		return nil
	}
	defer rows.Close()
	for rows.Next() {
		com := &model.Comment{}
		//Icontent,username,create_time
		err := rows.Scan(&com.UserName, &com.Email, &com.Content, &com.CreateTime)
		if err != nil {
			fmt.Println("db.SelectComments--->", err.Error())
			continue
		}
		comments = append(comments, com)
	}
	return
}
